﻿using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace ui
{
    internal class TcpServer
    {
        // 设置Log信息委托
        public delegate void LogMessage(string s);
        
        public LogMessage LogShow;
        private TcpClient _tcpClient;
        private readonly byte[] _buffer = new byte[1024];
        public int State { set; get; } // 0 未连接 1连接中 2已经连接 3连接失败/关闭

        public TcpServer(string ip, int port)
        {
            _ip = ip;
            _port = port;
        }

        private readonly string _ip;
        private readonly int _port;

        public void Start()
        {
            //先写个单线程的
            try
            {
                _tcpClient = new TcpClient();
                var result = _tcpClient.BeginConnect(IPAddress.Parse(_ip), _port, null, null);
                State = 1;
                var connectResult = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));

                if (!connectResult)
                {
                    LogShow(_ip + "/" + _port + ":Connect refused.");
                   // _tcpClient.EndConnect(result);
                    State = 3;
                    return;
                }
                State = 2;
                LogShow(_ip + "/" + _port + ":Connected.");
                var reader = new BinaryReader(_tcpClient.GetStream());
                while (true)         //TCP线程监听
                {
                    try
                    {
                        var len = reader.Read(_buffer, 0, 1024);
                        if (len == 0)
                        {
                            break;
                        }
                        //Console.WriteLine("上位机上传数据");
                        //for (int i = 0; i < len; i++)
                        //{
                        //    Console.Write(_buffer[i].ToString());
                        //}
                        //Console.WriteLine("");
                        ParseUtil.Parse_updata(_buffer, len);          //接收到内容交给解析函数处理后上传
                        LogShow(System.Text.Encoding.ASCII.GetString(_buffer,3,len));
                    }
                    catch (Exception e)
                    {
                        //Console.WriteLine("break with {0}\r\n", e.Message);
                        break;
                    }
                }
                _tcpClient.EndConnect(result);
                State = 3;
                LogShow(_ip + "/" + _port + ":Closed.");
            }
            catch (Exception e)
            {
                
            }
        }

        public void Send(string s)
        {
            if (State == 2)
            {
                var writer = new BinaryWriter(_tcpClient.GetStream());
                writer.Write(System.Text.Encoding.ASCII.GetBytes(s));
            }
            else
            {
                LogShow("No Connection.");
            }
        }

        public void Stop()
        {
            if (State == 2)
            {
                _tcpClient.Close();
                State = 3;
                LogShow("Connection close.");
            }
        }

    }


}
